// 唤醒子进程，若程序中需要在主进程中唤醒其它子进程在这里处理

import common from 'mv-common';
import { spawn, ChildProcess } from 'child_process';

class PrinterSDK {
    #childProcess: ChildProcess | null = null;
    public verifyTimeList = [100, 500, 1000, 2000];

    // 需要启动的子进程的启动目录
    public get appPath() {
        return '';
    }

    // 返回需要启动的子进程名称, 进程名称
    public get childrenProcessName() {
        return '';
    }

    // 启动子进程
    public async run() {
        return new Promise((resolve) => {
            this.closeAppServices().finally(() => {
                this.#childProcess = spawn(this.appPath);
                this.#childProcess = null;
                return resolve(true);
            });
        });
    }

    // 关闭子进程
    public closeServer() {
        return Promise.resolve();
    }

    // 关闭子进程
    public async closeAppServices() {
        return new Promise((resolve) => {
            if (!this.childrenProcessName) return resolve(true);

            common
                .isActiveProcessByName(this.childrenProcessName)
                .then((isActive) => {
                    if (!isActive) return resolve(true);
                    this.closeServer().finally(() => {
                        common.killProcessName(this.childrenProcessName);
                        resolve(true);
                    });
                })
                .catch(() => {
                    this.closeServer().finally(() => resolve(true));
                });
        }).then((value) => {
            this.#childProcess = null;
            return value;
        });
    }
}

export default new PrinterSDK();
